package com.example.xgsweather.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.example.xgsweather.R;
import com.example.xgsweather.util.LocationUtil;
import com.example.xgsweather.util.LogUtil;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Range;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.view.QWeather;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends BaseActivity {

    private String weatherId = null;
    private String countyName = null;
    private int mPosition = 0;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showProgressDialog();
        // 申请权限
        if (LocationUtil.checkAndBuildPermissions(this)) {
            return;
        }
        getCityFromSharedPreferences();
    }

    private void getCityFromSharedPreferences() {
        // 对缓存数据的判断，如果不为null就说明之前已经请求过天气数据了，就没必要再次选择城市，直接跳转到WeatherActivity即可
        SharedPreferences prefs = getSharedPreferences("current_city", Context.MODE_PRIVATE);
        if (prefs.getString("weather_id", null) != null) {
            weatherId = prefs.getString("weather_id", null);
            countyName = prefs.getString("county_name", null);
            mPosition = prefs.getInt("position", 0);
            toWeatherActivity();
        } else {
            autoGetCity();
        }
    }

    private void autoGetCity() {
        if ("".equals(weatherId) || weatherId == null) {
            String loc = LocationUtil.autoGetLocation(this);
            if ("".equals(loc) || loc == null) {
                toWeatherActivity();
                return;
            }
            QWeather.getGeoCityLookup(this, loc, Range.CN, 1, null, new QWeather.OnResultGeoListener() {
                @Override
                public void onError(Throwable e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toWeatherActivity();
                        }
                    });
                    LogUtil.e("LocationUtil doSearchArea onError: " + e);
                }

                @Override
                public void onSuccess(GeoBean geoBean) {
                    if (Code.OK == geoBean.getCode()) {
                        List<GeoBean.LocationBean> resultLocationBeans = geoBean.getLocationBean();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                weatherId = resultLocationBeans.get(0).getId();
                                countyName = resultLocationBeans.get(0).getName();
                                toWeatherActivity();
                                LogUtil.w("自动获取定位：[ " + weatherId + ", " + countyName + " ]");
                            }
                        });
                    } else {
                        //在此查看返回数据失败的原因
                        Code code = geoBean.getCode();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                toWeatherActivity();
                            }
                        });
                        LogUtil.e("LocationUtil doSearchArea failed code: " + code);
                    }
                }
            });
        }
    }

    private void toWeatherActivity() {
        // 检查网络连接
        ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        if (!(networkInfo != null && networkInfo.isAvailable())) {
            new AlertDialog.Builder(this)
                    .setTitle("请先连接网络才能使用app获取天气信息！")
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
            return;
        }
        if (weatherId != null && !("".equals(weatherId))) {
            Intent intent = new Intent(this, WeatherFragmentActivity.class);
            intent.putExtra("weather_id", weatherId);
            intent.putExtra("county_name", countyName);
            intent.putExtra("position", mPosition);
            startActivity(intent);
            closeProgressDialog();
            finish();
        } else {
            closeProgressDialog();
            Toast.makeText(this, "获取定位失败，请选择城市", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        LogUtil.w("onRequestPermissionsResult: permissions:" + Arrays.toString(permissions)
                + ",grantResults:" + Arrays.toString(grantResults));
        boolean isNeedCheckPermissions = true;
        if (grantResults.length > 0) {
            for (int result : grantResults) {
                if (PackageManager.PERMISSION_GRANTED == result) {
                    isNeedCheckPermissions = false;
                    break;
                }
            }
        }
        SharedPreferences.Editor pe = getSharedPreferences("app_settings", Context.MODE_PRIVATE).edit();
        pe.putBoolean("isNeedCheckPermissions", isNeedCheckPermissions);
        pe.apply();
        getCityFromSharedPreferences();
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在获取定位...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

}
